package com.tensai.core.config;


import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Rest接口配置，现在仅仅用于HTTP请求
 *
 * @author Tensai
 */
@Configuration
public class RestConfig {

//    @Bean
//    public RestTemplate restTemplate(){
//        // -------------------------------> 解决(响应数据可能)中文乱码 的问题
//        RestTemplate restTemplate = new RestTemplate();;
//        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//        converterList.remove(1); // 移除原来的转换器
//        // 设置字符编码为utf-8
//        HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
//        // 添加新的转换器(注:convert顺序错误会导致失败)
//        converterList.add(1, converter);
//        restTemplate.setMessageConverters(converterList);
//        return restTemplate;
//    }
//
//    @Bean("urlConnection")
//    public RestTemplate urlConnectionRestTemplate(){
//        return new RestTemplate(new SimpleClientHttpRequestFactory());
//    }
//
//    @Bean
//    public RestTemplate httpClientRestTemplate(){
//        return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
//    }

    /**
     * 配置基于OKHTTP3的访问模板
     *
     * @return  RestTemplate
     */
    @Bean
    public RestTemplate oKHttp3RestTemplate() {
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        // 移除原来的转换器
        converterList.remove(1);
        // 设置字符编码为utf-8
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        // 添加新的转换器(注:convert顺序错误会导致失败)
        converterList.add(1, converter);
        restTemplate.setMessageConverters(converterList);
        return restTemplate;
    }
}

